<template>
  <div>
    <template v-for="(item, index) in state.options">
      <template v-if="values.includes(item[state.value])">
        <el-tag :key="index * 2" :disable-transitions="true" :index="index" type="primary">
          {{ item[state.label] }}
        </el-tag>
      </template>
    </template>
  </div>
</template>

<script setup lang="ts" name="DictTag">
import { computed, onMounted, reactive } from "vue";
import { api } from "@/api/common/";

const props = defineProps({
  dictCode: {
    type: String,
    default: function () {
      return "100";
    }
  },
  options: {
    type: Array,
    default: function () {
      return [];
    }
  },
  queryUrl: {
    type: String,
    default: function () {
      return "/admin/dictentry/get/list";
    }
  },
  // 当前的值
  value: { type: [Number, String, Array], default: null }
});

const state = reactive({
  options: [],
  label: "label",
  value: "value"
});

onMounted(async () => {
  await initQuery();
});

const initQuery = async () => {
  if (props.options) {
    state.options = props.options;
    state.label = "label";
    state.value = "value";
  } else {
    state.label = "dictText";
    state.value = "dictValue";
    const queryParams = { dictCode: props.dictCode };
    api(props.queryUrl, queryParams)
      .then(res => {
        state.options = res.data;
      })
      .catch(err => {
        console.log(`easy-dict-select:${err}`);
      });
  }
};

const values = computed(() => {
  if (props.value !== null && typeof props.value !== "undefined") {
    return Array.isArray(props.value) ? props.value : [String(props.value)];
  } else {
    return [];
  }
});
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
